package main.java.indi.zyj.sword;

public class SpiralArray {


    public int[] spiralArray(int[][] array) {

        int row = array.length, col = array[0].length;
        int top = 0, bottom = row - 1, left = 0, right = col - 1;

        int[] res = new int[row * col];
        int index = 0;

        while (top <= bottom && left <= right) {
            for (int i = left; i <= right; i++) {
                res[index++] = array[top][i];
            }
            for (int i = top + 1; i <= bottom; i++) {
                res[index++] = array[i][right];
            }
            if (top < bottom && left < right) {
                for (int i = right - 1; i > left; i--) {
                    res[index++] = array[bottom][i];
                }
                for (int i = bottom - 1; i > top; i--) {
                    res[index++] = array[i][left];
                }
            }
            top++;
            bottom--;
            left++;
            right--;
        }

        return res;

    }


}
